make_directory("$ENV{DESTDIR}${CMAKE_INSTALL_PREFIX}/package/Library/Application Support/obs-studio/plugins")

if(EXISTS "$ENV{DESTDIR}${CMAKE_INSTALL_PREFIX}/@CMAKE_PROJECT_NAME@.plugin" AND NOT IS_SYMLINK "$ENV{DESTDIR}${CMAKE_INSTALL_PREFIX}/@CMAKE_PROJECT_NAME@.plugin")
  file(INSTALL DESTINATION "$ENV{DESTDIR}${CMAKE_INSTALL_PREFIX}/package/Library/Application Support/obs-studio/plugins"
    TYPE DIRECTORY FILES "$ENV{DESTDIR}${CMAKE_INSTALL_PREFIX}/@CMAKE_PROJECT_NAME@.plugin" USE_SOURCE_PERMISSIONS)

  if(CMAKE_INSTALL_CONFIG_NAME MATCHES "^([Rr][Ee][Ll][Ee][Aa][Ss][Ee])$" OR CMAKE_INSTALL_CONFIG_NAME MATCHES "^([Mm][Ii][Nn][Ss][Ii][Zz][Ee][Rr][Ee][Ll])$")
    if(EXISTS "$ENV{DESTDIR}${CMAKE_INSTALL_PREFIX}/@CMAKE_PROJECT_NAME@.plugin.dSYM" AND NOT IS_SYMLINK "$ENV{DESTDIR}${CMAKE_INSTALL_PREFIX}/@CMAKE_PROJECT_NAME@.plugin.dSYM")
      file(INSTALL DESTINATION "$ENV{DESTDIR}${CMAKE_INSTALL_PREFIX}/package/Library/Application Support/obs-studio/plugins" TYPE DIRECTORY FILES "$ENV{DESTDIR}${CMAKE_INSTALL_PREFIX}/@CMAKE_PROJECT_NAME@.plugin.dSYM" USE_SOURCE_PERMISSIONS)
    endif()
  endif()
endif()

make_directory("$ENV{DESTDIR}${CMAKE_INSTALL_PREFIX}/temp")

# Copy the post-installation script to the package directory and set permission to execute
# This leaves some leftover files if the script / install fails and shoul dbe looked-at properly before being re-enabled.
# file(COPY "${CMAKE_CURRENT_SOURCE_DIR}/cmake/macos/resources/scripts" DESTINATION "$ENV{DESTDIR}${CMAKE_INSTALL_PREFIX}/package/scripts")
# file(INSTALL DESTINATION "$ENV{DESTDIR}${CMAKE_INSTALL_PREFIX}/package/scripts" TYPE FILE FILES "${CMAKE_CURRENT_SOURCE_DIR}/cmake/macos/resources/scripts" PERMISSIONS OWNER_EXECUTE OWNER_WRITE OWNER_READ GROUP_EXECUTE GROUP_READ WORLD_EXECUTE WORLD_READ)

# Add the files to the pkgutil build to consider them
# --scripts "$ENV{DESTDIR}${CMAKE_INSTALL_PREFIX}/package/scripts"
# or directly adding the script files in the command line 
# --scripts "${CMAKE_CURRENT_SOURCE_DIR}/cmake/macos/resources/scripts"


execute_process(
  COMMAND /usr/bin/pkgbuild
    --identifier '@MACOS_BUNDLEID@'
    --version '@CMAKE_PROJECT_VERSION@'
    --root "$ENV{DESTDIR}${CMAKE_INSTALL_PREFIX}/package"
    "$ENV{DESTDIR}${CMAKE_INSTALL_PREFIX}/temp/@CMAKE_PROJECT_NAME@.pkg"
    COMMAND_ERROR_IS_FATAL ANY
  )

execute_process(
  COMMAND /usr/bin/productbuild
    --distribution "@CMAKE_CURRENT_BINARY_DIR@/distribution"
    --package-path "$ENV{DESTDIR}${CMAKE_INSTALL_PREFIX}/temp"
    "$ENV{DESTDIR}${CMAKE_INSTALL_PREFIX}/@CMAKE_PROJECT_NAME@.pkg"
    COMMAND_ERROR_IS_FATAL ANY)

if(EXISTS "$ENV{DESTDIR}${CMAKE_INSTALL_PREFIX}/@CMAKE_PROJECT_NAME@.pkg")
 file(REMOVE_RECURSE "$ENV{DESTDIR}${CMAKE_INSTALL_PREFIX}/temp")
 file(REMOVE_RECURSE "$ENV{DESTDIR}${CMAKE_INSTALL_PREFIX}/package")
endif()

